import { defineStore } from 'pinia'
import request from '@/utils/request'
import { topCategory } from '../constants'
import { CateItem , ApiRes,TopCategory,SubCategory } from '@/types/data'
// 导入常量默认数据 遍历得到 数组包对象
const defaultCate = topCategory.map((item) => {
  return { name: item }
})

const useCategoryStore = defineStore('category', {
  //共享数据
  state() {
    return {
      cateList: defaultCate as CateItem[], //分类数据
      topCategory: {} as TopCategory,//一级分类
      subCategory:{ } as SubCategory ,//二级商品分类
    }
  },
  actions: {
    async getCateList() {
      const res = await request.get<ApiRes<CateItem[]>>('/home/category/head')
      res.data.result.forEach(item=>item.show=false)
      this.cateList = res.data.result
    },
    show(id:string){
      this.cateList.find(item=>item.id===id)!.show=true
    },
    hide(id:string){
      this.cateList.find(item=>item.id===id)!.show=false
    },
    // 一级分类详情
    async getTopCategory(id: string) {
      const res = await request.get<ApiRes<TopCategory>>('/category', {
        params: {
          id,
        },
      })
      this.topCategory = res.data.result
    },
    // 二级数据详情
    async getSubFilter(id: string) {
      const res = await request.get<ApiRes<SubCategory>>(
        '/category/sub/filter',
        {
          params: {
            id,
          },
        }
      )
      this.subCategory = res.data.result
    },
  },
  getters: {},
})
export default useCategoryStore
